package com.sos.service;

import com.sos.exception.CustomException;
import com.sos.exception.ErrorCode;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class VerifyCodeService {

    private final RedisTemplate<String, Object> redisTemplate;

    // 发送间隔：60秒
    private static final long SEND_INTERVAL_SECONDS = 60;
    // 验证码有效期：3分钟（180秒）
    private static final long CODE_EXPIRATION_SECONDS = 180;

    /**
     * 生成6位数字验证码
     */
    public String generateCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    /**
     * 存储验证码到Redis，设置发送间隔和有效期
     */
    public void saveCode(String email, String code) {
        String key = "sos:verify:code:" + email;
        // 检查是否在发送间隔内（60秒）
        if (Boolean.TRUE.equals(redisTemplate.hasKey(key))) {
            throw new CustomException(ErrorCode.CODE_SEND_TOO_FREQUENTLY,
                    "验证码发送过于频繁，请" + SEND_INTERVAL_SECONDS + "秒后再试");
        }
        // 存储验证码，设置有效期为3分钟
        redisTemplate.opsForValue().set(key, code, CODE_EXPIRATION_SECONDS, TimeUnit.SECONDS);
    }

    /**
     * 验证验证码是否正确
     */
    public void validateCode(String email, String code) {
        String key = "sos:verify:code:" + email;
        String storedCode = (String) redisTemplate.opsForValue().get(key);

        if (storedCode == null) {
            throw new CustomException(ErrorCode.INVALID_VERIFICATION_CODE);
        }

        if (!storedCode.equals(code)) {
            throw new CustomException(ErrorCode.INVALID_VERIFICATION_CODE);
        }

        // 验证成功后删除验证码，防止重复使用
        redisTemplate.delete(key);
    }

}